﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace BalancaDummie
{
    public partial class frmServidor : Form
    {
        private Object thislock = new Object();
        delegate void SetTextCallback(string text);

        Balanca balanca;

        public frmServidor()
        {
            InitializeComponent();
            Thread.CurrentThread.Name = "ServerForm";
        }

        private void frmServidor_Load(object sender, EventArgs e)
        {
            this.FormClosing += new FormClosingEventHandler(frmServidor_FormClosing);
            Log("Servidor iniciado");
            btnIniciar.PerformClick();
        }

        void frmServidor_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (balanca != null)
                balanca.Parar();
        }

        private void btnIniciar_Click(object sender, EventArgs e)
        {
            if (balanca == null)
            {
                var porta = Convert.ToInt16(txtPorta.Text);
                balanca = new Balanca(porta);
                balanca.Tara = Convert.ToInt16(txtTara.Text);

                balanca.StatusChanged += new StatusChangeEventHandler(balanca_StatusChanged);
            }
            balanca.Iniciar();

            AlternaBotoesServidor();
            AlternaBotoesEmbarque();
        }

        private void btnParar_Click(object sender, EventArgs e)
        {
            balanca.Parar();

            AlternaBotoesServidor();
            AlternaBotoesEmbarque();
        }

        private void btnIniciarEmbarque_Click(object sender, EventArgs e)
        {
            int total = Int32.Parse(txtPeso.Text);

            if (balanca != null && balanca.IsListening)
            {

                if (balanca.Embarque == null || balanca.Embarque.Finalizado)
                    balanca.Embarque = new Embarque(total);

                MudarPorao();

                balanca.IniciarEmbarque();

                AlternaBotoesEmbarque();

                Thread ThreadVerificador = new Thread(new ThreadStart(VerificarEmbarque));
                ThreadVerificador.Name = "VerificadorDeEmbarque";
                ThreadVerificador.Start();
            }
        }

        private void btnPararEmbarque_Click(object sender, EventArgs e)
        {
            if (balanca.Embarque != null)
            {
                balanca.Embarque.Embarcando = false;

                AlternaBotoesEmbarque(); 
            }
        }

        private void cmbPorao_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        private void MudarPorao()
        {
            balanca.Embarque.PoraoAtual = Convert.ToInt16(cmbPorao.Text);

            Log("Embarcando no porão " + cmbPorao.Text);
        }

        private void AlternaBotoesServidor()
        {
            btnIniciar.Enabled = !balanca.IsListening;
            btnParar.Enabled = balanca.IsListening;
            txtPorta.Enabled = !balanca.IsListening;
        }

        private void AlternaBotoesEmbarque()
        {
            if (balanca.Embarque != null)
            {
                btnIniciarEmbarque.Enabled = !balanca.Embarque.Embarcando && !btnIniciar.Enabled;
                btnPararEmbarque.Enabled = balanca.Embarque.Embarcando;

                txtPeso.Enabled = txtTara.Enabled = balanca.Embarque.Finalizado;
                cmbPorao.Enabled = !balanca.Embarque.Embarcando;
            }
            else
                btnIniciarEmbarque.Enabled = btnParar.Enabled;
        }

        public void VerificarEmbarque()
        {
            while (balanca.Embarque.Embarcando)
            {
                continue;
            }

            MethodInvoker action = delegate
            {
                AlternaBotoesEmbarque();
            };

            try
            {
                lock (thislock)
                {
                    Invoke(action);
                }
            }
            catch (ObjectDisposedException)
            {
                Thread.CurrentThread.Interrupt();
            }
        }

        void balanca_StatusChanged(object sender, BalancaEventArgs e)
        {
            Log(e.Status);
        }

        private void Log(string p)
        {
            string msg = p;

            if (txtServerStatus.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(Log);
                Invoke(d, new object[] { msg });
            }
            else
            {
                txtServerStatus.Text += DateTime.Now.ToLongTimeString() + " -> " + msg + Environment.NewLine;
                lblBalancaStatus.Text = msg;

                txtServerStatus.SelectionStart = txtServerStatus.Text.Length;
                txtServerStatus.ScrollToCaret();
            }
        }

        private void debugmsg(string p)
        {
            System.Diagnostics.Debug.WriteLine("Servidor Form " + DateTime.Now.ToLongTimeString() + " -> " + p);
        }
    }
}
